# Copyright (C) 2025 All rights reserved.
#   
# @File notification.py
# @Brief 
# @Author 杨嘉祥, vnimy@mediad.cn
# @Version 1.0
# @Date 2025-01-26
#
import frappe
import json
from frappe.utils import unique
from frappe.email.doctype.notification.notification import Notification as NotificationOrigin
from frappe_wxwork.message import send_wxwork_message


class Notification(NotificationOrigin):
    def create_system_notification(self, doc, context):
        super().create_system_notification(doc, context)

        subject = self.subject
        if "{" in subject:
            subject = frappe.render_template(self.subject, context)

        recipients, cc, bcc = self.get_list_of_recipients(doc, context)

        users = unique(recipients + cc + bcc)

        if not users:
            return
        
        doc = {
            "title": subject,
            "content": frappe.render_template(self.wxwork_message, context),
            "message_type": self.wxwork_msgtype,
        }

        if self.send_to_wxwork:
            frappe.enqueue(
                "frappe_wxwork.message.send_wxwork_message",
                doc=doc,
                users=users,
                # now=frappe.flags.in_test,
                now=True
            )
